
package com.syu.loopcure.compensator.aop;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.syu.loopcure.common.exception.CompensatorBusinessException;
import com.syu.loopcure.compensator.enums.StatusEnum;
import com.syu.loopcure.compensator.interfaces.ICompensatorRecord;
import com.syu.loopcure.compensator.model.CompensatorInfoModel;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.List;

/**  
 * ClassName: CompensatorAspect <br/>
 * date: 2020年8月11日 下午6:04:18 <br/>  
 *  
 * @author zhucun
 * @since JDK 1.8  
 */
@Aspect
@Component
public class CompensatorAspect {
	
	private final ICompensatorRecord compensatorRecord;

	@Autowired
	public CompensatorAspect(ICompensatorRecord compensatorRecord){
		this.compensatorRecord = compensatorRecord;
	}

	@AfterThrowing(value = "com.syu.loopcure.compensator.aop.CompensatorPointCut.exceptionPointCut()",throwing="e")
	public void afterThrowing(JoinPoint point, CompensatorBusinessException e) {
		MethodSignature signature = (MethodSignature) point.getSignature();
		Method method = signature.getMethod();
		// 构建待补偿对象
		CompensatorInfoModel compensatorInfoModel = new CompensatorInfoModel(method,point.getArgs(),e.getFailMessage());
		// 注解解析
        CompensatorLog compensatorLog = method.getAnnotation(CompensatorLog.class);
        // 补偿最大尝试次数
        int maxRetryTimes = compensatorLog.maxRetryTimes();
        compensatorInfoModel.setMaxRetryTimes(maxRetryTimes);
        // 补偿重试时间间隔
        String waitSeconds = compensatorLog.waitSeconds();
        compensatorInfoModel.setWaitSeconds(waitSeconds);
        
        // 判断新增或者更新
        List<CompensatorInfoModel> oldModelList = compensatorRecord.findRecordByUniqueKey(compensatorInfoModel.getMd5Code());
        if(CollectionUtils.isEmpty(oldModelList)) {
        	// 新增
        	// 重试次数
        	compensatorInfoModel.setRetryTimes(0);
        	// 补偿状态
        	compensatorInfoModel.setStatus(StatusEnum.FAIL_NEED_COMPENSATOR.getCode());
        	// 创建时间
        	compensatorInfoModel.setCreateTime(new Date());
        	compensatorRecord.addRecord2Db(compensatorInfoModel);
        }else {
        	// 重试后仍然失败，更新
        	// 重试结束时间
        	compensatorInfoModel.setRetryEndTime(new Date());
        	if(maxRetryTimes > oldModelList.get(0).getRetryTimes()) {
        		compensatorInfoModel.setStatus(StatusEnum.FAIL_NEED_COMPENSATOR.getCode());
        	}else {
        		compensatorInfoModel.setStatus(StatusEnum.MAXIMUM_NUMBER_OF_TIMES_COMPENSATOR.getCode());
        	}
        	// 更新时间
        	compensatorInfoModel.setModifyTime(new Date());
        	compensatorRecord.updateRecord2Db(compensatorInfoModel);
        }
	}
}
  
